package edu.base.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.base.dao.UserMapper;
import edu.base.model.Users;
import edu.base.util.Result;
import edu.base.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    UserMapper userMapper;



    //手机验证码登录
    @Override
    public Result<Users> loginPh(String phoneNum){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("tel",phoneNum);
        if(userMapper.selectCount(wrapper)>0){
            Users user = userMapper.selectOne(wrapper);
            if(user.getState()==1){
                return Result.success(user);
            }else{
                return Result.failure(ResultCode.NOT_LOGIN_FAIL);
            }
        }
        return Result.failure(ResultCode.USER_NOT_FOUND);

    }

    /*
    登录
        根据手机/用户名查询用户信息
     */
    @Override
    public Result<Users> loginUser(String content, String pwd) {
        Users user = userMapper.loginSelect(content);
        if(user!=null){
            if(user.getLoginPwd().equals(DigestUtils.md5DigestAsHex(pwd.getBytes()))){
            //if(pwd.equals(user.getLoginPwd())){
                return Result.success(user);
            }else{
                //密码错误
                return Result.failure(ResultCode.LOGIN_PASSWORD_ERROR);
            }


        }
        //用户不存在
        return Result.failure(ResultCode.USER_NOT_FOUND);
    }

    /*忘记密码
     * 2.输入手机号发送验证码
     * 3.修改密码
     * */
    @Override
    public Result updatePassword(String pwd,String phone) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("tel",phone);
        if(userMapper.selectCount(wrapper) > 0){
            Users updateUser = new Users();
            updateUser.setLoginPwd(DigestUtils.md5DigestAsHex(pwd.getBytes()));                                //DigestUtils.md5DigestAsHex(pwd.getBytes()));
            userMapper.update(updateUser,wrapper);
            return Result.success();
        }
        return Result.failure(ResultCode.USER_NOT_FOUND);
    }



}
